# Replication code for:
# Winning at all costs? How negative partisanship affects voter decision-making
# Study 1

# packages ####
library(dplyr)
library(cregg)
library(ggplot2)
library(xtable)
library(estimatr)
library(sjPlot)
library(marginaleffects)

# To replicate the analyses, set your working directory to the replication folder that contains the datasets. A default working directory is currently set to a folder called "POBE Replication Files_Strategic Voting" on your Desktop. 
setwd("~/Desktop/POBE Replication Files_Strategic Voting/")


# DATA CLEANING -------------- ####

# load data ####
dat <- read.csv("study1_data.csv")

# pass attention check to complete survey
dat <- subset(dat, attentioncheck1==3)

# recode pid3 including leaners ####
dat$pid3<-NA
dat$pid3[dat$pid==1 | dat$pid_ind==1] <- "Democrat"
dat$pid3[dat$pid==2 | dat$pid_ind==2] <- "Republican"
dat$pid3[dat$pid==3 & dat$pid_ind==3] <- "Independent"
dat$pid3[dat$pid==4 & dat$pid_ind==3] <- "Independent"
dat$pid3[dat$pid==5 & dat$pid_ind==3] <- "Independent"
dat$pid3 <- as.factor(dat$pid3)
table(dat$pid3)

# recode party win (Appendix) ####
dat$partywin_dems <- car::recode(dat$partywin_dems, "5=1; 6=2; 3=3; 2=4")
dat$partywin_repubs <- car::recode(dat$partywin_repubs, "5=1; 6=2; 3=3; 2=4")
dat$partywin_dems[dat$partywin_dems==""] <- NA
dat$partywin_repubs[dat$partywin_repubs==""] <- NA

dat <- dat %>%
  mutate(partywin = coalesce(partywin_repubs, partywin_dems))

dat$partywin_level <- NA
dat$partywin_level[dat$partywin==3 | dat$partywin==4] <- "Important"
dat$partywin_level[dat$partywin==1 | dat$partywin==2] <- "Not Important"
dat$partywin_level <- as.factor(dat$partywin_level)


# recode feeling thermomters ####

# remove pid3 NAs
dat <- subset(dat, !is.na(dat$pid3))

dat$feelingtherm_outparty <- NA
dat$feelingtherm_outparty[dat$pid3=="Democrat"] <- dat$feelingtherm_repubs[dat$pid3=="Democrat"]
dat$feelingtherm_outparty[dat$pid3=="Republican"] <- dat$feelingtherm_dems[dat$pid3=="Republican"]
table(dat$pid3)

dat$feelingtherm_inparty <- NA
dat$feelingtherm_inparty[dat$pid3=="Democrat"] <- dat$feelingtherm_dems[dat$pid3=="Democrat"]
dat$feelingtherm_inparty[dat$pid3=="Republican"] <- dat$feelingtherm_repubs[dat$pid3=="Republican"]

# net partisan affect (inparty rating minus outparty rating)
dat$netaffect <- (dat$feelingtherm_inparty - dat$feelingtherm_outparty)


# create outparty level ####
out_cutoff <- quantile(dat$feelingtherm_outparty, probs = c(.10), na.rm=TRUE)[[1]]
# 10 percentile = 0 

dat$outparty_level <- NA
dat$outparty_level[dat$feelingtherm_outparty==out_cutoff] <- "High in NP"
dat$outparty_level[dat$feelingtherm_outparty > out_cutoff] <- "Everyone else"
dat$outparty_level<-as.factor(dat$outparty_level)

table(dat$outparty_level, dat$pid3)

# create inparty level  ####
in_cutoff <- quantile(dat$feelingtherm_inparty, probs = c(.90), na.rm=TRUE)[[1]]
# 90 percentile = 100 

dat$inparty_level <- NA
dat$inparty_level[dat$feelingtherm_inparty==in_cutoff] <- "High in PP"
dat$inparty_level[dat$feelingtherm_inparty < in_cutoff] <- "Everyone else"
dat$inparty_level<-as.factor(dat$inparty_level)

# create netaffect level (Appendix) ####
netlow_cutoff <- quantile(dat$netaffect, probs = c(.10), na.rm=TRUE)[[1]]
nethigh_cutoff <- quantile(dat$netaffect, probs = c(.90), na.rm=TRUE)[[1]]

dat$netaffect_level <- NA
dat$netaffect_level[dat$netaffect>nethigh_cutoff] <- "High Net Neg Affect"
dat$netaffect_level[dat$netaffect < netlow_cutoff] <- "Low Net Neg Affect"
dat$netaffect_level<-as.factor(dat$netaffect_level)

# different thresholds for robustness (Appendix) ####
dat$outparty_level010 <- NA
dat$outparty_level010[dat$feelingtherm_outparty<11] <- "High in NP (0-10)"
dat$outparty_level010[dat$feelingtherm_outparty>10] <- "Everyone else (>10)"
dat$outparty_level010<-as.factor(dat$outparty_level010)
table(dat$outparty_level010, dat$pid3)

dat$inparty_level90100 <- NA
dat$inparty_level90100[dat$feelingtherm_inparty>89] <- "High in PP (90-100)"
dat$inparty_level90100[dat$feelingtherm_inparty<90] <- "Everyone else (<90)"
dat$inparty_level90100<-as.factor(dat$inparty_level90100)

# DESCRIPTIVES, CORRELATIONS --------------------- ####

# remove true independents ####
dat <- subset(dat, pid3!="Independent")

# Table C1 ####
prop.table(table(dat$race))
prop.table(table(dat$gender))
prop.table(table(dat$pid3))
prop.table(table(dat$edu))

# Table 1 ####
summary(dat$feelingtherm_outparty)
sd(dat$feelingtherm_outparty, na.rm=TRUE)
summary(dat$feelingtherm_inparty)
sd(dat$feelingtherm_inparty, na.rm=TRUE)

# Table E1 ####
cor.test(dat$feelingtherm_outparty, dat$feelingtherm_inparty)
cor.test(dat$feelingtherm_outparty, dat$partywin)
cor.test(dat$feelingtherm_inparty, dat$partywin)

# SET UP CONJOINT DATA --------------- #### 

# combine dem and repub DVs ####
dat <-dat %>%
  mutate(vote1 = coalesce(vote_repub1, vote_dem1),
         vote2 = coalesce(vote_repub2, vote_dem2),
         vote3 = coalesce(vote_repub3, vote_dem3),
         vote4 = coalesce(vote_repub4, vote_dem4),
         vote5 = coalesce(vote_repub5, vote_dem5),
         vote6 = coalesce(vote_repub6, vote_dem6),
         sincere1 = coalesce(sincere_repub1, sincere_dem1),
         sincere2 = coalesce(sincere_repub2, sincere_dem2),
         sincere3 = coalesce(sincere_repub3, sincere_dem3),
         sincere4 = coalesce(sincere_repub4, sincere_dem4),
         sincere5 = coalesce(sincere_repub5, sincere_dem5),
         sincere6 = coalesce(sincere_repub6, sincere_dem6))

# recode candidate ideology ####
dat <- dat %>%
  mutate(across(c("ideology_demA_1", "ideology_demB_1", "ideology_demA_2", "ideology_demB_2", "ideology_demA_3", "ideology_demB_3", "ideology_demA_4", "ideology_demB_4", "ideology_demA_5", "ideology_demB_5", "ideology_demA_6", "ideology_demB_6"), 
                ~ recode(., "Rated 1 (very liberal)"="1", 
                         "Rated 2 (solidly liberal)"="2",
                         "Rated 3 (somewhat liberal)"="3",
                         "Rated 4 (moderate)"="4",
                         "Rated 5 (somewhat conservative)"="5")))

dat <- dat %>%
  mutate(across(c("ideology_repubA_1", "ideology_repubB_1", "ideology_repubA_2", "ideology_repubB_2", "ideology_repubA_3", "ideology_repubB_3","ideology_repubA_4", "ideology_repubB_4","ideology_repubA_5", "ideology_repubB_5","ideology_repubA_6", "ideology_repubB_6"),
                ~recode(.,"Rated 1 (very conservative)"="7",
                        "Rated 2 (solidly conservative)"="6",
                        "Rated 3 (somewhat conservative)"="5",
                        "Rated 4 (moderate)"="4",
                        "Rated 5 (somewhat liberal)"="3")))

# combine dem and repub ideology ####
dat$ideologyA_1[dat$pid3=="Democrat"] <- dat$ideology_demA_1[dat$pid3=="Democrat"]
dat$ideologyA_1[dat$pid3=="Republican"] <- dat$ideology_repubA_1[dat$pid3=="Republican"]
dat$ideologyB_1[dat$pid3=="Democrat"] <- dat$ideology_demB_1[dat$pid3=="Democrat"]
dat$ideologyB_1[dat$pid3=="Republican"] <- dat$ideology_repubB_1[dat$pid3=="Republican"]

dat$ideologyA_2[dat$pid3=="Democrat"] <- dat$ideology_demA_2[dat$pid3=="Democrat"]
dat$ideologyA_2[dat$pid3=="Republican"] <- dat$ideology_repubA_2[dat$pid3=="Republican"]
dat$ideologyB_2[dat$pid3=="Democrat"] <- dat$ideology_demB_2[dat$pid3=="Democrat"]
dat$ideologyB_2[dat$pid3=="Republican"] <- dat$ideology_repubB_2[dat$pid3=="Republican"]

dat$ideologyA_3[dat$pid3=="Democrat"] <- dat$ideology_demA_3[dat$pid3=="Democrat"]
dat$ideologyA_3[dat$pid3=="Republican"] <- dat$ideology_repubA_3[dat$pid3=="Republican"]
dat$ideologyB_3[dat$pid3=="Democrat"] <- dat$ideology_demB_3[dat$pid3=="Democrat"]
dat$ideologyB_3[dat$pid3=="Republican"] <- dat$ideology_repubB_3[dat$pid3=="Republican"]

dat$ideologyA_4[dat$pid3=="Democrat"] <- dat$ideology_demA_4[dat$pid3=="Democrat"]
dat$ideologyA_4[dat$pid3=="Republican"] <- dat$ideology_repubA_4[dat$pid3=="Republican"]
dat$ideologyB_4[dat$pid3=="Democrat"] <- dat$ideology_demB_4[dat$pid3=="Democrat"]
dat$ideologyB_4[dat$pid3=="Republican"] <- dat$ideology_repubB_4[dat$pid3=="Republican"]

dat$ideologyA_5[dat$pid3=="Democrat"] <- dat$ideology_demA_5[dat$pid3=="Democrat"]
dat$ideologyA_5[dat$pid3=="Republican"] <- dat$ideology_repubA_5[dat$pid3=="Republican"]
dat$ideologyB_5[dat$pid3=="Democrat"] <- dat$ideology_demB_5[dat$pid3=="Democrat"]
dat$ideologyB_5[dat$pid3=="Republican"] <- dat$ideology_repubB_5[dat$pid3=="Republican"]

dat$ideologyA_6[dat$pid3=="Democrat"] <- dat$ideology_demA_6[dat$pid3=="Democrat"]
dat$ideologyA_6[dat$pid3=="Republican"] <- dat$ideology_repubA_6[dat$pid3=="Republican"]
dat$ideologyB_6[dat$pid3=="Democrat"] <- dat$ideology_demB_6[dat$pid3=="Democrat"]
dat$ideologyB_6[dat$pid3=="Republican"] <- dat$ideology_repubB_6[dat$pid3=="Republican"]


# stack conjoint trials ####
trial1a <- dplyr::select(dat, starts_with("feelingtherm"), "vote1", "sincere1", "nameA_1", "winA_1", "ideologyA_1", "ageA_1","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial1a <- dplyr::rename(trial1a, "vote"="vote1",
                         "sincere"="sincere1",
                         "name"="nameA_1", 
                         "win"="winA_1",
                         "ideology"="ideologyA_1",
                         "age"="ageA_1")

trial1a$vote[trial1a$vote==2] <- 0
trial1a$sincere[trial1a$sincere==2] <- 0

trial1b <- dplyr::select(dat, starts_with("feelingtherm"), "vote1", "sincere1", "nameB_1", "winB_1", "ideologyB_1", "ageB_1","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial1b <- dplyr::rename(trial1b, "vote"="vote1",
                         "sincere"="sincere1",
                         "name"="nameB_1", 
                         "win"="winB_1",
                         "ideology"="ideologyB_1",
                         "age"="ageB_1")

trial1b$vote[trial1b$vote==1] <- 0
trial1b$vote[trial1b$vote==2] <- 1

trial1b$sincere[trial1b$sincere==1] <- 0
trial1b$sincere[trial1b$sincere==2] <- 1


trial2a <- dplyr::select(dat, starts_with("feelingtherm"), "vote2", "sincere2", "nameA_2", "winA_2", "ideologyA_2", "ageA_2","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")

trial2a <- dplyr::rename(trial2a, "vote"="vote2",
                         "sincere"="sincere2",
                         "name"="nameA_2", 
                         "win"="winA_2",
                         "ideology"="ideologyA_2",
                         "age"="ageA_2")

trial2a$vote[trial2a$vote==2] <- 0
trial2a$sincere[trial2a$sincere==2] <- 0

trial2b <- dplyr::select(dat, starts_with("feelingtherm"), "vote2", "sincere2", "nameB_2", "winB_2", "ideologyB_2", "ageB_2","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")

trial2b <- dplyr::rename(trial2b, "vote"="vote2",
                         "sincere"="sincere2",
                         "name"="nameB_2", 
                         "win"="winB_2",
                         "ideology"="ideologyB_2",
                         "age"="ageB_2")

trial2b$vote[trial2b$vote==1] <- 0
trial2b$vote[trial2b$vote==2] <- 1

trial2b$sincere[trial2b$sincere==1] <- 0
trial2b$sincere[trial2b$sincere==2] <- 1


trial3a <- dplyr::select(dat, starts_with("feelingtherm"), "vote3", "sincere3", "nameA_3", "winA_3", "ideologyA_3", "ageA_3","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial3a <- dplyr::rename(trial3a, "vote"="vote3",
                         "sincere"="sincere3",
                         "name"="nameA_3", 
                         "win"="winA_3",
                         "ideology"="ideologyA_3",
                         "age"="ageA_3")

trial3a$vote[trial3a$vote==2] <- 0
trial3a$sincere[trial3a$sincere==2] <- 0

trial3b <- dplyr::select(dat, starts_with("feelingtherm"), "vote3", "sincere3", "nameB_3", "winB_3", "ideologyB_3", "ageB_3","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial3b <- dplyr::rename(trial3b, "vote"="vote3",
                         "sincere"="sincere3",
                         "name"="nameB_3", 
                         "win"="winB_3",
                         "ideology"="ideologyB_3",
                         "age"="ageB_3")

trial3b$vote[trial3b$vote==1] <- 0
trial3b$vote[trial3b$vote==2] <- 1

trial3b$sincere[trial3b$sincere==1] <- 0
trial3b$sincere[trial3b$sincere==2] <- 1


trial4a <- dplyr::select(dat, starts_with("feelingtherm"), "vote4", "sincere4", "nameA_4", "winA_4", "ideologyA_4", "ageA_4","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial4a <- dplyr::rename(trial4a, "vote"="vote4",
                         "sincere"="sincere4",
                         "name"="nameA_4", 
                         "win"="winA_4",
                         "ideology"="ideologyA_4",
                         "age"="ageA_4")

trial4a$vote[trial4a$vote==2] <- 0
trial4a$sincere[trial4a$sincere==2] <- 0

trial4b <- dplyr::select(dat, starts_with("feelingtherm"), "vote4", "sincere4", "nameB_4", "winB_4", "ideologyB_4", "ageB_4","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial4b <- dplyr::rename(trial4b, "vote"="vote4",
                         "sincere"="sincere4",
                         "name"="nameB_4", 
                         "win"="winB_4",
                         "ideology"="ideologyB_4",
                         "age"="ageB_4")

trial4b$vote[trial4b$vote==1] <- 0
trial4b$vote[trial4b$vote==2] <- 1

trial4b$sincere[trial4b$sincere==1] <- 0
trial4b$sincere[trial4b$sincere==2] <- 1


trial5a <- dplyr::select(dat, starts_with("feelingtherm"), "vote5", "sincere5", "nameA_5", "winA_5", "ideologyA_5", "ageA_5","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial5a <- dplyr::rename(trial5a, "vote"="vote5",
                         "sincere"="sincere5",
                         "name"="nameA_5", 
                         "win"="winA_5",
                         "ideology"="ideologyA_5",
                         "age"="ageA_5")

trial5a$vote[trial5a$vote==2] <- 0
trial5a$sincere[trial5a$sincere==2] <- 0

trial5b <- dplyr::select(dat, starts_with("feelingtherm"), "vote5", "sincere5", "nameB_5", "winB_5", "ideologyB_5", "ageB_5","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial5b <- dplyr::rename(trial5b, "vote"="vote5",
                         "sincere"="sincere5",
                         "name"="nameB_5", 
                         "win"="winB_5",
                         "ideology"="ideologyB_5",
                         "age"="ageB_5")

trial5b$vote[trial5b$vote==1] <- 0
trial5b$vote[trial5b$vote==2] <- 1

trial5b$sincere[trial5b$sincere==1] <- 0
trial5b$sincere[trial5b$sincere==2] <- 1


trial6a <- dplyr::select(dat, starts_with("feelingtherm"), "vote6", "sincere6", "nameA_6", "winA_6", "ideologyA_6", "ageA_6","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu", "ideo7", "ResponseId")


trial6a <- dplyr::rename(trial6a, "vote"="vote6",
                         "sincere"="sincere6",
                         "name"="nameA_6", 
                         "win"="winA_6",
                         "ideology"="ideologyA_6",
                         "age"="ageA_6")

trial6a$vote[trial6a$vote==2] <- 0
trial6a$sincere[trial6a$sincere==2] <- 0

trial6b <- dplyr::select(dat, starts_with("feelingtherm"), "vote6", "sincere6", "nameB_6", "winB_6", "ideologyB_6", "ageB_6","attentioncheck2_1", "attentioncheck2_5", "outparty_level","inparty_level","netaffect_level", "partywin", "partywin_level", "pid3","gender.1", "edu","ideo7", "ResponseId")


trial6b <- dplyr::rename(trial6b, "vote"="vote6",
                         "sincere"="sincere6",
                         "name"="nameB_6",
                         "win"="winB_6",
                         "ideology"="ideologyB_6",
                         "age"="ageB_6")

trial6b$vote[trial6b$vote==1] <- 0
trial6b$vote[trial6b$vote==2] <- 1

trial6b$sincere[trial6b$sincere==1] <- 0
trial6b$sincere[trial6b$sincere==2] <- 1

# stack
datstacked <- rbind(trial1a, trial1b, trial2a, trial2b, trial3a, trial3b, trial4a, trial4b, trial5a, trial5b, trial6a, trial6b)

datstacked <- droplevels(datstacked)

# merge in race + gender for names #####
names <- read.csv("butler_homola_names_coded.csv")

datstacked <- merge(datstacked, names, by.x="name", by.y="Name")

# recode ideological proximity ####
datstacked$ideology <- as.numeric(datstacked$ideology)
table(datstacked$ideology)

datstacked$cand_ideo_distance <- abs(datstacked$ideology-datstacked$ideo7)

datstacked$cand_ideo_distance <- as.factor(datstacked$cand_ideo_distance)

datstacked$cand_ideo_distance_2 <- NA
datstacked$cand_ideo_distance_2[datstacked$cand_ideo_distance=="0"] <- 0
datstacked$cand_ideo_distance_2[datstacked$cand_ideo_distance=="1"] <- 1
datstacked$cand_ideo_distance_2[datstacked$cand_ideo_distance=="2"] <- 2
datstacked$cand_ideo_distance_2[datstacked$cand_ideo_distance=="3"] <- 3
datstacked$cand_ideo_distance_2[datstacked$cand_ideo_distance=="4" | datstacked$cand_ideo_distance=="5" | datstacked$cand_ideo_distance=="6"] <- "≥4"

datstacked$cand_ideo_distance_2 <- factor(datstacked$cand_ideo_distance_2, levels=c("≥4", "3", "2", "1", "0"))

# numeric version
datstacked$cand_ideo_distance.num <- as.numeric(as.character(datstacked$cand_ideo_distance))
table(datstacked$cand_ideo_distance.num)
table(datstacked$cand_ideo_distance)

# recode candidate ideology with labels #####
datstacked$cand_ideology <- dplyr::recode(datstacked$ideology,
                                          '1' = "Very liberal",
                                          '2' = "Solidly liberal",
                                          '3' = "Somewhat liberal",
                                          '4' = "Moderate",
                                          '5' = "Somewhat conservative",
                                          '6' = "Solidly conservative",
                                          '7' = "Very conservative")
# relevel candidate ideology
datstacked$cand_ideology <- factor(datstacked$cand_ideology,levels = c("Very liberal", "Solidly liberal", "Somewhat liberal", "Moderate", "Somewhat conservative", "Solidly conservative", "Very conservative"))


# recode age ####
datstacked$age_group <- NA
datstacked$age_group[datstacked$age<40] <- "35-39"
datstacked$age_group[datstacked$age>39 & datstacked$age<50] <- "40s"
datstacked$age_group[datstacked$age>49 & datstacked$age<60] <- "50s"
datstacked$age_group[datstacked$age>59 & datstacked$age<70] <- "60s"
datstacked$age_group[datstacked$age>69] <- "70-75"
table(datstacked$age_group)

# recode gender ####
datstacked$cand_gender<- NA
datstacked$cand_gender[datstacked$female==0] <- "Man"
datstacked$cand_gender[datstacked$female==1] <- "Woman"

# recode race ####
datstacked$cand_race<- NA
datstacked$cand_race[datstacked$race=="W"] <- "White"
datstacked$cand_race[datstacked$race=="B"] <- "Black"
datstacked$cand_race[datstacked$race=="L"] <- "Latino/a"

# recode electability #### 
datstacked$win[datstacked$win=="does NOT have"] <- "Lose"
datstacked$win[datstacked$win=="has"] <- "Win"

# recode ideo7 (respondent) with categorical labels #####
datstacked$respondent_ideo7 <- dplyr::recode(datstacked$ideo7,
                                             '1' = "Very liberal",
                                             '2' = "Liberal",
                                             '3' = "Somewhat liberal",
                                             '4' = "Moderate",
                                             '5' = "Somewhat conservative",
                                             '6' = "Conservative",
                                             '7' = "Very conservative")

# relevel respondent_ideo7
datstacked$respondent_ideo7 <- factor(datstacked$respondent_ideo7, levels = c("Very liberal", "Liberal", "Somewhat liberal", "Moderate", "Somewhat conservative", "Conservative", "Very conservative"))

# convert to factor variables
datstacked$age_group <- as.factor(datstacked$age_group)
datstacked$win <- as.factor(datstacked$win)
datstacked$cand_race <- as.factor(datstacked$cand_race)
datstacked$cand_gender <- as.factor(datstacked$cand_gender)
datstacked$respondent_ideo7 <- as.factor(datstacked$respondent_ideo7)
datstacked$cand_ideology <- as.factor(datstacked$cand_ideology)


# RESULTS -------- #####

# the trade off ####
datstacked$tradeoff <- NA
datstacked$tradeoff <- ifelse(datstacked$vote==datstacked$sincere, 0, 1)

## % of time that respondents select the same candidate for strategic/sincere #
prop.table(table(datstacked$tradeoff))
# 0.86956022 they select the same candidate
# 0.1304398 they make a trade-off

# H1, H2, H2a, H2b (main effects) ####

## AMCES (Appendix H) ####

# vote choice (DV1):
amce <- cj(datstacked, vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="amce")

p1 <- plot(amce,
           feature_headers = FALSE,
           vline=0, vline_color = "grey30", 
           feature_labels=FALSE,
           size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Average Marginal Component Effect")+
  theme_minimal() +
  theme(legend.position="none", plot.title=element_text(size=12),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Vote for (strategic choice)")+
  scale_x_continuous(limits=c(-0.25, 0.50)) +
  scale_colour_manual(values=c("black", "black","black","black","black"))+
  scale_shape_manual(values=c(16, 16, 1, 1, 1))+
  aes(shape = feature)

p1

# represents interests best (DV2):
amce2 <- cj(datstacked, sincere ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="amce")

p2 <- plot(amce2,
           feature_headers = FALSE,
           vline=0, vline_color = "grey30", 
           feature_labels=FALSE,
           size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Average Marginal Component Effect")+
  theme_minimal() +
  theme(legend.position="none", plot.title=element_text(size=12),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Thinks represents best (sincere choice)")+
  scale_x_continuous(limits=c(-0.25, 0.50)) +
  scale_colour_manual(values=c("black", "black","black","black","black")) +
  scale_shape_manual(values=c(16, 16, 1, 1, 1))+
  aes(shape = feature)

p2


## MMS ####

# vote choice (DV1):
mm <- cj(datstacked, vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm")

# Figure 1 ####
# vote choice (DV1) JUST ELECTABILITY AND IDEO:

mm_subset <- subset(mm, feature=="Ideological Proximity" | feature=="Chance of Winning")

p3 <- plot(mm_subset,
           feature_headers = FALSE,
           vline=.5, vline_color = "grey30", 
           feature_labels=FALSE,
           size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="none", plot.title=element_text(size=12),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Vote for (strategic choice)")+
  scale_x_continuous(limits=c(0,1)) +
  scale_colour_manual(values=c("black", "black","black","black","black"))+
  scale_shape_manual(values=c(16, 16, 1, 1, 1))+
  aes(shape = feature)


#png("plot_mm_vote_2.png", height=4.3, width=4.5, units="in", res=350)
#p3
#dev.off()

# Table F1 ####
mmtable <- subset(mm, select=c(outcome, feature, level, estimate, std.error, lower, upper))
print(xtable(mmtable), include.rownames=FALSE)

# Sincere choice (Appendix G) ####

# represents interests best (DV2):
mm2 <- cj(datstacked, sincere ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm")

p4 <- plot(mm2,
           feature_headers = FALSE,
           vline=.5, vline_color = "grey30", 
           feature_labels=FALSE,
           size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="none", plot.title=element_text(size=12),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Thinks represents best (sincere choice)")+
  scale_x_continuous(limits=c(0.29, 0.7), breaks=c(.3,.4,.5,.6,.7)) +
  scale_colour_manual(values=c("black", "black","black","black","black"))+
  scale_shape_manual(values=c(16, 16, 1, 1, 1))+
  aes(shape = feature)

mm2table <- subset(mm2, select=c(outcome, feature, level, estimate, std.error, lower, upper))
print(xtable(mm2table), include.rownames=FALSE)

# represents interests best (DV2) JUST ELECTABILITY AND IDEO:
mm2_subset <- subset(mm2, feature=="Ideological Proximity" | feature=="Chance of Winning")

p4 <- plot(mm2_subset,
           feature_headers = FALSE,
           vline=.5, vline_color = "grey30", 
           feature_labels=FALSE,
           size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="none", plot.title=element_text(size=12),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Thinks represents best (sincere choice)")+
  scale_x_continuous(limits=c(0,1)) +
  scale_colour_manual(values=c("black", "black","black","black","black"))+
  scale_shape_manual(values=c(16, 16, 1, 1, 1))+
  aes(shape = feature)


#png("plot_mm_sincere_2.png", height=4.3, width=4.5, units="in", res=350)
#p4
#dev.off()

# RESULTS BY NEGATIVE PARTISANSHIP ####

# vote choice (DV1):
mm3 <- cj(datstacked, vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", by=~outparty_level)

# Table F3 ####
mm3table <- subset(mm3, select=c(outparty_level, outcome, feature, level, estimate, std.error, lower, upper))
print(xtable(mm3table), include.rownames=FALSE)

mm3 <- subset(mm3, feature=="Chance of Winning" | feature=="Ideological Proximity" )

# Figure 2 ####
mm3plot <- plot(mm3,
                feature_headers = FALSE,
                vline=.5, vline_color = "grey30", 
                feature_labels=FALSE,
                size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Vote for (strategic choice)")+
  scale_x_continuous(limits=c(0, 1)) +
  scale_colour_manual(values=c("black", "black"))+
  scale_shape_manual(values=c(1, 16))+
  guides(color = "legend")+
  aes(shape = BY)+
  aes(colour = BY)

#png("plot_mm_vote_negparty.png", height=4.3, width=4.5, units="in", res=350)
#mm3plot
#dev.off()

#### Different thresholds (Appendix I) ####

# 20%, 40%, 60%... 
datstacked$outparty_quants <- cut(datstacked$feelingtherm_outparty, breaks = quantile(datstacked$feelingtherm_outparty, probs = c(0, .20, .40, .60, .80, 1), na.rm=TRUE), include.lowest = TRUE, labels = c("0-20%", "21-40%", "41-60%", "61-80%", "81-100%"))

quants <- cj(datstacked, vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", by=~outparty_quants)

quants <- subset(quants, feature=="Chance of Winning" | feature=="Ideological Proximity" )

quantsplot <- plot(quants,
                    feature_headers = FALSE,
                    vline=.5, vline_color = "grey30", 
                    feature_labels=FALSE,
                    size=1) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title = element_blank(),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Vote for (strategic choice)")+
  scale_x_continuous(limits=c(0, 1)) +
  scale_shape_manual(
    values = c(19, 18, 17, 15, 1),
    breaks = c("0-20%", "21-40%",  "41-60%",  "61-80%", "81-100%"),
    labels = c("0-20% \n(0-1)", "21-40% \n(1-7)",  "41-60% \n(8-22)",  "61-80% \n(22-42)", "81-100% \n(45-100)")) +
  scale_color_manual(
    values = c("#F8766D", "#B79F00", "#00BA38", "#00BFC4", "#619CFF"),
    breaks = c("0-20%", "21-40%",  "41-60%",  "61-80%", "81-100%"),
    labels = c("0-20% \n(0-1)", "21-40% \n(1-7)",  "41-60% \n(8-22)",  "61-80% \n(22-42)", "81-100% \n(45-100)")) +
  guides(color = "legend")+
  aes(shape = BY)+
  aes(colour = BY)
quantsplot

#png("plot_mm_vote_negparty_quintiles.png", height=5, width=5, units="in", res=350)
#quantsplot
#dev.off()

# Sincere choice (Appendix G) ####
mm4 <- cj(datstacked, sincere ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", by=~outparty_level)

#subset only to main 2 attributes
mm4 <- subset(mm4, feature=="Chance of Winning" | feature=="Ideological Proximity" )

mm4plot <- plot(mm4,
                feature_headers = FALSE,
                vline=.5, vline_color = "grey30", 
                feature_labels=FALSE,
                size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Thinks represents best (sincere choice)")+
  scale_x_continuous(limits=c(0.165, 0.8), breaks=c(.2,.3,.4,.5,.6,.7,.8)) +
  scale_colour_manual(values=c("black", "black"))+
  scale_shape_manual(values=c(1, 16))+
  guides(color = "legend")+
  aes(shape = BY)+
  aes(colour = BY)


#png("plot_mm_sincere_negparty.png", height=4.3, width=4.5, units="in", res=350)
#mm4plot
#dev.off()

# OTHER MEASURES ####

### partywin (Appendix L) ####

mm5 <- cj(datstacked, vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", by=~partywin_level)

mm5 <- subset(mm5, feature=="Chance of Winning" | feature=="Ideological Proximity" )

mm5plot <- plot(mm5,
           feature_headers = FALSE,
           vline=.5, vline_color = "grey30", 
           feature_labels=FALSE,
           size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Vote for (strategic choice)")+
  scale_x_continuous(limits=c(0.2, 0.8), breaks=c(.2,.3,.4,.5,.6,.7,.8)) +
  scale_colour_manual(values=c("black", "black"))+
  scale_shape_manual(values=c(16, 1))+
  guides(color = "legend")+
  aes(shape = BY)+
  aes(colour = BY)


#png("plot_mm_vote_partywin.png", height=5, width=4.5, units="in", res=350)
#mm5plot
#dev.off()


### netaffect (Appendix K)####

mm_net <- cj(datstacked, vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", by=~netaffect_level)

mm_net <- subset(mm_net, feature=="Chance of Winning" | feature=="Ideological Proximity" )

mm_netplot <- plot(mm_net,
                feature_headers = FALSE,
                vline=.5, vline_color = "grey30", 
                feature_labels=FALSE,
                size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Vote for (strategic choice)")+
  scale_x_continuous(limits=c(0.2, 0.8), breaks=c(.2,.3,.4,.5,.6,.7,.8)) +
  scale_colour_manual(values=c("black", "black"))+
  scale_shape_manual(values=c(16, 1))+
  guides(color = "legend")+
  aes(shape = BY)+
  aes(colour = BY)


#png("plot_mm_vote_netaffect.png", height=4.3, width=4.5, units="in", res=350)
#mm_netplot
#dev.off()

# RESULTS BY POSITIVE PARTISANSHIP ####

# Figure 3 ####
mm_inparty <- cj(datstacked, vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", by=~inparty_level)

mm_inparty <- subset(mm_inparty, feature=="Chance of Winning" | feature=="Ideological Proximity" )

mm_inpartyplot <- plot(mm_inparty,
                feature_headers = FALSE,
                vline=.5, vline_color = "grey30", 
                feature_labels=FALSE,
                size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  xlab("Marginal Mean")+
  theme_minimal() +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  ggtitle("Vote for (strategic choice)")+
  scale_x_continuous(limits=c(0.2, 0.8), breaks=c(.2,.3,.4,.5,.6,.7,.8)) +
  scale_colour_manual(values=c("black", "black"))+
  scale_shape_manual(values=c(1, 16))+
  guides(color = "legend")+
  aes(shape = BY)+
  aes(colour = BY)


#png("plot_mm_vote_posparty.png", height=4.3, width=4.5, units="in", res=350)
#mm_inpartyplot
# dev.off()

# TRADE OFF ----------- #####

win_ideo <- lm_robust(vote ~ win*outparty_level*cand_ideo_distance_2, data = datstacked, cluster = ResponseId)

summary(win_ideo)

# Figure 5 ####
p<-plot_model(win_ideo, type = "pred", terms = c("cand_ideo_distance_2", "outparty_level", "win"), show.values=TRUE, 
              ci.lvl = .95, 
              colors=c("grey30", "black")) +
  geom_line(size=.4) + theme_minimal()+geom_hline(yintercept=0.5, linetype="dashed", color = "grey70")+
  labs(title = "", y="Predicted vote", x="Ideological Proximity \n (distance in units on scale)") + 
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text.x = element_text(size=8),
        axis.text.y = element_text(size=10), 
        strip.text = element_text(size = 10)) +
  aes(shape = group) +
  aes(color = group) +
  scale_shape_manual(values = c(1, 16))+
  guides(color = "legend") +
  guides(shape = "legend")

p

#png("vote_negparty_flipped.png", height=4, width=5, units="in", res=350)
#p
#dev.off()

# Table of results (Appendix F)
get_model_data(win_ideo, type = "pred", terms = c("cand_ideo_distance_2", "win", "outparty_level"))

win_ideotable <- get_model_data(win_ideo, type = "pred", terms = c("cand_ideo_distance_2", "win", "outparty_level"))
names(win_ideotable)
win_ideotable <- subset(win_ideotable, select=c(x, facet, group, predicted, std.error, conf.low, conf.high))
print(xtable(win_ideotable), include.rownames=FALSE)

## Different thresholds (Appendix I) ####

win_ideo_quants <- lm_robust(vote ~ win*outparty_quants*cand_ideo_distance_2, data = datstacked, cluster = ResponseId)

p<-plot_model(win_ideo_quants, type = "pred", terms = c("cand_ideo_distance_2", "outparty_quants", "win"), show.values=TRUE, 
              ci.lvl = .95, dodge = .8) + 
  theme_minimal()+ geom_hline(yintercept=0.5, linetype="dashed", color = "grey70")+
  labs(title = "", y="Predicted vote", x="Ideological Proximity \n (distance in units on scale)") + 
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text.x = element_text(size=8),
        axis.text.y = element_text(size=10), 
        strip.text = element_text(size = 10)) +
  aes(shape = group) +
  aes(color = group) +
  scale_shape_manual(
    values = c(19, 18, 17, 15, 1),
    breaks = c("0-20%", "21-40%",  "41-60%",  "61-80%", "81-100%"),
    labels = c("0-20% \n(0-1)", "21-40% \n(1-7)",  "41-60% \n(8-22)",  "61-80% \n(22-42)", "81-100% \n(45-100)")) +
  scale_color_manual(
    values = c("#F8766D", "#B79F00", "#00BA38", "#00BFC4", "#619CFF"),
    breaks = c("0-20%", "21-40%",  "41-60%",  "61-80%", "81-100%"),
    labels = c("0-20% \n(0-1)", "21-40% \n(1-7)",  "41-60% \n(8-22)",  "61-80% \n(22-42)", "81-100% \n(45-100)")) +
  guides(color = "legend") +
  guides(shape = "legend")

p

#png("vote_negparty_flipped_quintiles.png", height=5.5, width=7, units="in", res=350)
#p
#dev.off()


## Candidate ideology (Appendix O) ####

win_ideo_si <- lm_robust(vote ~ win*outparty_level*cand_ideology, data = datstacked, cluster = ResponseId)

summary(win_ideo_si)

p<-plot_model(win_ideo_si, type = "pred", terms = c("cand_ideology", "outparty_level", "win"), show.values=TRUE, 
              ci.lvl = .95, 
              colors=c("grey30", "black")) +
  geom_line(size=.4) + theme_minimal()+geom_hline(yintercept=0.5, linetype="dashed", color = "grey70")+
  labs(title = "", y="Predicted vote", x="Candidate Ideology") + 
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text.x = element_text(size=8, angle = 45, hjust = 1),
        axis.text.y = element_text(size=10), 
        strip.text = element_text(size = 10)) +
  aes(shape = group) +
  aes(color = group) +
  scale_shape_manual(values = c(1, 16))+
  guides(color = "legend") +
  guides(shape = "legend")

p


#png("vote_negparty_flipped_candideo.png", height=4, width=5, units="in", res=350)
#p
#dev.off()


## Candidate ideology x Respondent ideology (Appendix O) ####

datstacked$cand_ideology_labels <- ifelse(datstacked$cand_ideology == "Very liberal", "1",
                                          ifelse(datstacked$cand_ideology == "Solidly liberal", "2",
                                                 ifelse(datstacked$cand_ideology == "Somewhat liberal", "3",
                                                        ifelse(datstacked$cand_ideology == "Moderate", "4",
                                                               ifelse(datstacked$cand_ideology == "Somewhat conservative", "5",
                                                                      ifelse(datstacked$cand_ideology == "Solidly conservative", "6",
                                                                             ifelse(datstacked$cand_ideology == "Very conservative", "7", NA)
                                                                      )
                                                               )
                                                        )
                                                 )
                                          )
)


win_ideo_si <- lm_robust(vote ~ win*respondent_ideo7*cand_ideology_labels, data = datstacked, cluster = ResponseId)

summary(win_ideo_si)

p<-plot_model(win_ideo_si, type = "pred", terms = c("cand_ideology_labels", "win", "respondent_ideo7"), show.values=TRUE, 
              ci.lvl = .95, 
              colors=c("grey30", "black")) +
  geom_line(size=.3) + theme_minimal()+
  geom_hline(yintercept=0.5, linetype="dashed", color = "grey70")+
  labs(title = "Respondent Ideology", y="Predicted vote", x="Candidate Ideology \n (Very liberal - Very conservative)") + 
  theme(legend.position="bottom", 
        legend.title=element_blank())+
  aes(shape = group) +
  aes(color = group)+
  scale_shape_manual(values = c(1, 20))+
  guides(color = "legend") +
  guides(shape = "legend")

p

#png("vote_respondentideo_candideo_flipped.png", height=5, width=5, units="in", res=350)
#p
#dev.off()

# Marginal effects ------------ #####

## Figure 4 ####

model1 <- lm_robust(vote ~ win*cand_ideo_distance_2*feelingtherm_outparty, data = datstacked, cluster = ResponseId)

summary(model1)

tab_model(model1)
model1table <- model1 %>% tidy
model1table <- subset(model1table, select=c(term, estimate, std.error, p.value))
print(xtable(model1table), include.rownames=FALSE)


modelplot <- plot_cme(model1, variables="win", condition=c("feelingtherm_outparty"))+
  theme_minimal() +geom_hline(yintercept=0.0, linetype="dashed", color = "grey70")+
  labs(title = "Win vs. Lose", y="Marginal effect of electability", x="Outparty Rating") +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text.x = element_text(size=10),
        axis.text.y = element_text(size=10), 
        strip.text = element_text(size = 10)) 


#png("effectof_win_outparty_linear.png", height=4, width=4.5, units="in", res=350)
#modelplot
#dev.off()


## By partisan affiliation (Appendix M) ####

win_ideo_therm_pid <- lm_robust(vote ~ win*cand_ideo_distance_2*feelingtherm_outparty*pid3, data = datstacked, cluster = ResponseId)


plot <- plot_cme(win_ideo_therm_pid, variables="win", condition=c("feelingtherm_outparty", "pid3"))+
  theme_minimal() +
  labs(title = "Win vs. Lose by PID", y="Marginal effect of electability", x="Outparty Rating") +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text.x = element_text(size=10),
        axis.text.y = element_text(size=10), 
        strip.text = element_text(size = 10)) +
  scale_y_continuous(limits=c(-0.05, 0.4), breaks=c(0, .1, .2, .3, .4)) + scale_colour_manual(values=c("darkblue", "red")) + scale_fill_manual(values=c("dodgerblue", "pink"))
plot

#png("effectof_win_negparty_bypid.png", height=4, width=4, units="in", res=350)
#plot
#dev.off()


# Weighted adjustment (Appendix N)  --------- #####

## create weights ##

datstacked$weight <- NA

# Democrats
datstacked$weight[datstacked$ideo7==1 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="0"] <- 1
datstacked$weight[datstacked$ideo7==1 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="1"] <- 1
datstacked$weight[datstacked$ideo7==1 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="2"] <- 1
datstacked$weight[datstacked$ideo7==2 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="0"] <- 1.33
datstacked$weight[datstacked$ideo7==2 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="1"] <- 0.67
datstacked$weight[datstacked$ideo7==2 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="2"] <- 1.33
datstacked$weight[datstacked$ideo7==3 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="0"] <- 1.67
datstacked$weight[datstacked$ideo7==3 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="1"] <- 0.83
datstacked$weight[datstacked$ideo7==3 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="2"] <- 0.83
datstacked$weight[datstacked$ideo7==4 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="0"] <- 1.33
datstacked$weight[datstacked$ideo7==4 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="1"] <- 0.67
datstacked$weight[datstacked$ideo7==4 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="2"] <- 1.33
datstacked$weight[datstacked$ideo7==5 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="0"] <- 1
datstacked$weight[datstacked$ideo7==5 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="1"] <- 1
datstacked$weight[datstacked$ideo7==5 & datstacked$pid3=="Democrat" & datstacked$cand_ideo_distance_2=="2"] <- 1

# Republicans
datstacked$weight[datstacked$ideo7==7 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="0"] <- 1
datstacked$weight[datstacked$ideo7==7 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="1"] <- 1
datstacked$weight[datstacked$ideo7==7 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="2"] <- 1
datstacked$weight[datstacked$ideo7==6 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="0"] <- 1.33
datstacked$weight[datstacked$ideo7==6 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="1"] <- 0.67
datstacked$weight[datstacked$ideo7==6 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="2"] <- 1.33
datstacked$weight[datstacked$ideo7==5 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="0"] <- 1.67
datstacked$weight[datstacked$ideo7==5 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="1"] <- 0.83
datstacked$weight[datstacked$ideo7==5 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="2"] <- 0.83
datstacked$weight[datstacked$ideo7==4 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="0"] <- 1.33
datstacked$weight[datstacked$ideo7==4 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="1"] <- 0.67
datstacked$weight[datstacked$ideo7==4 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="2"] <- 1.33
datstacked$weight[datstacked$ideo7==3 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="0"] <- 1
datstacked$weight[datstacked$ideo7==3 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="1"] <- 1
datstacked$weight[datstacked$ideo7==3 & datstacked$pid3=="Republican" & datstacked$cand_ideo_distance_2=="2"] <- 1

## check new probabilities for ideological congruence ##
cj_props(subset(datstacked, pid3=="Democrat" & !is.na(weight)), ~ as.factor(cand_ideo_distance_2) + as.factor(ideo7), id = ~ ResponseId, weights = ~ weight)

cj_props(subset(datstacked, pid3=="Republican" & !is.na(weight)), ~ as.factor(cand_ideo_distance_2) + as.factor(ideo7), id = ~ ResponseId, weights = ~ weight)

## new results with weights ##
mm <- cj(subset(datstacked, !is.na(weight)), vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", weights= ~weight)

mm_subset <- subset(mm, !is.na(estimate) & feature=="Ideological Proximity" | feature=="Chance of Winning")

p <- plot(mm_subset,
           feature_headers = FALSE,
           vline=.5, vline_color = "grey30", 
           feature_labels=FALSE,
           size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  theme_minimal() +
  theme(legend.position="none", plot.title=element_text(size=12),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  labs(title="Vote for (strategic choice)", x="Marginal Mean", subtitle = "Adjusted for randomization constraints")+
  scale_x_continuous(limits=c(0.25,.75)) +
  scale_colour_manual(values=c("black", "black","black","black","black"))+
  scale_shape_manual(values=c(16, 16, 1, 1, 1))+
  aes(shape = feature)

p

#png("plot_mm_vote_weights.png", height=4, width=4, units="in", res=350)
#p
#dev.off()

mmtable <- subset(mm, select=c(outcome, feature, level, estimate, std.error, lower, upper))
print(xtable(mmtable), include.rownames=FALSE)


## MMS outparty ##

mm <- cj(subset(datstacked, !is.na(weight)), vote ~ cand_ideo_distance_2 + win + cand_race + cand_gender + age_group, id = ~ ResponseId, feature_labels = list(cand_ideo_distance_2="Ideological Proximity", win="Chance of Winning", cand_race="Candidate Race", cand_gender="Candidate Gender", age_group="Candidate Age"), estimate="mm", by=~outparty_level, weights=~weight)

mmtable <- subset(mm, select=c(outparty_level, outcome, feature, level, estimate, std.error, lower, upper))
print(xtable(mmtable), include.rownames=FALSE)

mm_subset <- subset(mm, !is.na(estimate) & feature=="Ideological Proximity" | feature=="Chance of Winning")

mmplot <- plot(mm_subset,
                feature_headers = FALSE,
                vline=.5, vline_color = "grey30", 
                feature_labels=FALSE,
                size=2) +  
  ggplot2::facet_wrap(~feature, ncol = 1L,scales = "free_y",
                      strip.position = "top") + 
  theme_minimal() +
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text=element_text(size=9),
        axis.title=element_text(size=9), 
        strip.text = element_text(size = 10)) +
  labs(title="Vote for (strategic choice)", x="Marginal Mean", subtitle = "Adjusted for randomization constraints")+
  scale_x_continuous(limits=c(0, 1)) +
  scale_colour_manual(values=c("black", "black"))+
  scale_shape_manual(values=c(1, 16))+
  guides(color = "legend")+
  aes(shape = BY)+
  aes(colour = BY)

mmplot

#png("plot_mm_vote_negparty_weights.png", height=4.3, width=4.5, units="in", res=350)
#mmplot
#dev.off()

## tradeoff predicted vote ###

win_ideo <- lm_robust(vote ~ win*outparty_level*cand_ideo_distance_2, data = datstacked, cluster = ResponseId, weights = weight)

summary(win_ideo)

p<-plot_model(win_ideo, type = "pred", terms = c("cand_ideo_distance_2", "outparty_level", "win"), show.values=TRUE, 
              ci.lvl = .95, 
              colors=c("grey30", "black")) +
  geom_line(size=.4) + theme_minimal()+geom_hline(yintercept=0.5, linetype="dashed", color = "grey70")+
  labs(title = "Trade-Offs", subtitle = "Adjusted for randomization constraints", y="Predicted vote", x="Ideological Proximity \n (distance in units on scale)") + 
  theme(legend.position="bottom", 
        plot.title=element_text(size=12),
        legend.title=element_blank(),
        axis.text.x = element_text(size=8),
        axis.text.y = element_text(size=10), 
        strip.text = element_text(size = 10)) +
  aes(shape = group) +
  aes(color = group) +
  scale_shape_manual(values = c(1, 16))+
  scale_x_reverse(breaks=c(2, 1, 0), labels=c("2", "1", "0"))+
  guides(color = "legend") +
  guides(shape = "legend")

p

#png("vote_negparty_flipped_weights.png", height=4, width=5, units="in", res=350)
#p
#dev.off()

### results table with weights ###
get_model_data(win_ideo, type = "pred", terms = c("cand_ideo_distance_2", "win", "outparty_level"))

win_ideotable <- get_model_data(win_ideo, type = "pred", terms = c("cand_ideo_distance_2", "win", "outparty_level"))
names(win_ideotable)
win_ideotable <- subset(win_ideotable, select=c(x, facet, group, predicted, std.error, conf.low, conf.high))
print(xtable(win_ideotable), include.rownames=FALSE)


